#include "dbdialog.h"
#include "ui_dbdialog.h"
#include "datahandler.h"
#include <QtSql/QtSql>
#include <QtGui>

DataHandler *data_Handler;

DBDialog::DBDialog(QWidget *parent, DataHandler *Handler) :
    QDialog(parent),
    ui(new Ui::DBDialog)
{
    ui->setupUi(this);

    ui->ConnectedLabel->hide();
    ui->sqliteButton->setChecked(true);
    ui->mysqlgroupBox->hide();

    data_Handler = Handler;

    connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(ConnectToDB()));
    connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));
}

DBDialog::~DBDialog()
{
    delete ui;
}

void DBDialog::ConnectToDB()
{
    if(ui->sqliteButton->isChecked())
    {
        data_Handler->dbName = ui->pathEdit->text();
        data_Handler->sqliteType = true;
    }
    else
    {
        data_Handler->dbName = ui->dbEdit->text();
        data_Handler->hostName = ui->hostEdit->text();
        data_Handler->portNumber = ui->portBox->value();
        data_Handler->userName = ui->userEdit->text();
        data_Handler->password = ui->passEdit->text();
        data_Handler->sqliteType = false;
    }

    if (!data_Handler->ConnectToDB()) {
        QMessageBox::critical(0, qApp->tr("Cannot open database"),	//Displays error if connection to database fails
            qApp->tr("Unable to establish a database connection.\n"
                     "Please check the path and try again."), QMessageBox::Ok);
    }
    else
    {
        ui->ConnectedLabel->show();
        ui->connectButton->setEnabled(false);
    }
}
